<template>
  <div class="integration-management">
    <el-tabs v-model="activeTab" class="integration-tabs">
      <!-- 系统集成 -->
      <el-tab-pane label="系统集成" name="system">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <el-input v-model="systemSearch" placeholder="搜索系统" style="width: 200px" clearable @clear="loadSystemList" />
              <el-button type="primary" @click="handleCreateSystem">新增系统</el-button>
            </div>
          </template>
          <el-table :data="systemList" border v-loading="systemLoading">
            <el-table-column prop="name" label="系统名称" min-width="150" />
            <el-table-column prop="code" label="系统编码" width="120" />
            <el-table-column prop="type" label="集成类型" width="120" />
            <el-table-column prop="url" label="接口地址" min-width="200" />
            <el-table-column prop="authType" label="认证方式" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
                  {{ row.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="syncInterval" label="同步周期" width="100" />
            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditSystem(row)">编辑</el-button>
                <el-button link type="primary" @click="handleTestSystem(row)">测试</el-button>
                <el-button link type="primary" @click="handleSyncSystem(row)">同步</el-button>
                <el-button link type="warning" @click="handleToggleSystem(row)">
                  {{ row.status === 'enabled' ? '禁用' : '启用' }}
                </el-button>
                <el-button link type="danger" @click="handleDeleteSystem(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="systemPage"
              v-model:page-size="systemPageSize"
              :total="systemTotal"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="loadSystemList"
              @current-change="loadSystemList"
            />
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 消息队列 -->
      <el-tab-pane label="消息队列" name="queue">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <el-input v-model="queueSearch" placeholder="搜索队列" style="width: 200px" clearable @clear="loadQueueList" />
              <el-button type="primary" @click="handleCreateQueue">新增队列</el-button>
            </div>
          </template>
          <el-table :data="queueList" border v-loading="queueLoading">
            <el-table-column prop="name" label="队列名称" min-width="150" />
            <el-table-column prop="type" label="队列类型" width="120" />
            <el-table-column prop="server" label="服务器地址" min-width="200" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
                  {{ row.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="consumerCount" label="消费者数" width="100" />
            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditQueue(row)">编辑</el-button>
                <el-button link type="primary" @click="handleMonitorQueue(row)">监控</el-button>
                <el-button link type="primary" @click="handlePurgeQueue(row)">清空</el-button>
                <el-button link type="warning" @click="handleToggleQueue(row)">
                  {{ row.status === 'enabled' ? '禁用' : '启用' }}
                </el-button>
                <el-button link type="danger" @click="handleDeleteQueue(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="queuePage"
              v-model:page-size="queuePageSize"
              :total="queueTotal"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="loadQueueList"
              @current-change="loadQueueList"
            />
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 监控告警 -->
      <el-tab-pane label="监控告警" name="monitor">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <el-input v-model="monitorSearch" placeholder="搜索监控" style="width: 200px" clearable @clear="loadMonitorList" />
              <el-button type="primary" @click="handleCreateMonitor">新增监控</el-button>
            </div>
          </template>
          <el-table :data="monitorList" border v-loading="monitorLoading">
            <el-table-column prop="name" label="监控名称" min-width="150" />
            <el-table-column prop="type" label="监控类型" width="120" />
            <el-table-column prop="target" label="监控对象" min-width="200" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'enabled' ? 'success' : 'info'">
                  {{ row.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alertCount" label="今日告警" width="100" />
            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditMonitor(row)">编辑</el-button>
                <el-button link type="primary" @click="handleTestMonitor(row)">测试</el-button>
                <el-button link type="primary" @click="handleViewHistory(row)">历史</el-button>
                <el-button link type="warning" @click="handleToggleMonitor(row)">
                  {{ row.status === 'enabled' ? '禁用' : '启用' }}
                </el-button>
                <el-button link type="danger" @click="handleDeleteMonitor(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="monitorPage"
              v-model:page-size="monitorPageSize"
              :total="monitorTotal"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="loadMonitorList"
              @current-change="loadMonitorList"
            />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 系统集成弹窗表单 -->
    <el-dialog v-model="systemDialogVisible" :title="systemDialogTitle" width="600px" destroy-on-close>
      <el-form :model="systemForm" :rules="systemRules" ref="systemFormRef" label-width="100px">
        <el-form-item label="系统名称" prop="name">
          <el-input v-model="systemForm.name" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="系统编码" prop="code">
          <el-input v-model="systemForm.code" placeholder="请输入系统编码" />
        </el-form-item>
        <el-form-item label="集成类型" prop="type">
          <el-select v-model="systemForm.type" placeholder="请选择集成类型">
            <el-option label="REST API" value="rest" />
            <el-option label="SOAP" value="soap" />
            <el-option label="数据库" value="db" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="接口地址" prop="url">
          <el-input v-model="systemForm.url" placeholder="请输入接口地址" />
        </el-form-item>
        <el-form-item label="认证方式" prop="authType">
          <el-select v-model="systemForm.authType" placeholder="请选择认证方式">
            <el-option label="Token" value="token" />
            <el-option label="Basic Auth" value="basic" />
            <el-option label="OAuth2" value="oauth2" />
            <el-option label="无" value="none" />
          </el-select>
        </el-form-item>
        <el-form-item label="同步周期" prop="syncInterval">
          <el-input v-model="systemForm.syncInterval" placeholder="如：5min/1h/1d" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="systemForm.remark" type="textarea" rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="systemDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveSystem">保存</el-button>
      </template>
    </el-dialog>

    <!-- 消息队列弹窗表单 -->
    <el-dialog v-model="queueDialogVisible" :title="queueDialogTitle" width="600px" destroy-on-close>
      <el-form :model="queueForm" :rules="queueRules" ref="queueFormRef" label-width="100px">
        <el-form-item label="队列名称" prop="name">
          <el-input v-model="queueForm.name" placeholder="请输入队列名称" />
        </el-form-item>
        <el-form-item label="队列类型" prop="type">
          <el-select v-model="queueForm.type" placeholder="请选择队列类型">
            <el-option label="RabbitMQ" value="rabbitmq" />
            <el-option label="Kafka" value="kafka" />
            <el-option label="RocketMQ" value="rocketmq" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务器地址" prop="server">
          <el-input v-model="queueForm.server" placeholder="请输入服务器地址" />
        </el-form-item>
        <el-form-item label="消费者数" prop="consumerCount">
          <el-input-number v-model="queueForm.consumerCount" :min="1" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="queueForm.remark" type="textarea" rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="queueDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveQueue">保存</el-button>
      </template>
    </el-dialog>

    <!-- 监控告警弹窗表单 -->
    <el-dialog v-model="monitorDialogVisible" :title="monitorDialogTitle" width="600px" destroy-on-close>
      <el-form :model="monitorForm" :rules="monitorRules" ref="monitorFormRef" label-width="100px">
        <el-form-item label="监控名称" prop="name">
          <el-input v-model="monitorForm.name" placeholder="请输入监控名称" />
        </el-form-item>
        <el-form-item label="监控类型" prop="type">
          <el-select v-model="monitorForm.type" placeholder="请选择监控类型">
            <el-option label="系统" value="system" />
            <el-option label="业务" value="business" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="监控对象" prop="target">
          <el-input v-model="monitorForm.target" placeholder="请输入监控对象" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="monitorForm.remark" type="textarea" rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="monitorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveMonitor">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSystemList, createSystem, updateSystem, deleteSystem, updateSystemStatus, testSystem, syncSystem,
  getQueueList, createQueue, updateQueue, deleteQueue, updateQueueStatus, monitorQueue, purgeQueue,
  getMonitorList, createMonitor, updateMonitor, deleteMonitor, updateMonitorStatus, testMonitor, getMonitorHistory
} from '@/api/message'

// 标签页
const activeTab = ref('system')

// 系统集成
const systemList = ref([])
const systemLoading = ref(false)
const systemPage = ref(1)
const systemPageSize = ref(20)
const systemTotal = ref(0)
const systemSearch = ref('')
const systemDialogVisible = ref(false)
const systemDialogTitle = ref('')
const systemFormRef = ref(null)
const systemForm = reactive({ id: '', name: '', code: '', type: '', url: '', authType: '', syncInterval: '', remark: '' })
const systemRules = {
  name: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入系统编码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择集成类型', trigger: 'change' }],
  url: [{ required: true, message: '请输入接口地址', trigger: 'blur' }],
  authType: [{ required: true, message: '请选择认证方式', trigger: 'change' }],
  syncInterval: [{ required: true, message: '请输入同步周期', trigger: 'blur' }]
}

const loadSystemList = async () => {
  try {
    systemLoading.value = true
    const res = await getSystemList({
      page: systemPage.value,
      pageSize: systemPageSize.value,
      search: systemSearch.value
    })
    systemList.value = res.data.list
    systemTotal.value = res.data.total
  } catch (error) {
    ElMessage.error('加载系统列表失败')
  } finally {
    systemLoading.value = false
  }
}

const handleCreateSystem = () => {
  systemDialogTitle.value = '新增系统'
  Object.assign(systemForm, { id: '', name: '', code: '', type: '', url: '', authType: '', syncInterval: '', remark: '' })
  systemDialogVisible.value = true
}
const handleEditSystem = (row) => {
  systemDialogTitle.value = '编辑系统'
  Object.assign(systemForm, row)
  systemDialogVisible.value = true
}
const handleSaveSystem = async () => {
  if (!systemFormRef.value) return
  try {
    await systemFormRef.value.validate()
    if (systemForm.id) {
      await updateSystem(systemForm)
      ElMessage.success('更新成功')
    } else {
      await createSystem(systemForm)
      ElMessage.success('创建成功')
    }
    systemDialogVisible.value = false
    loadSystemList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}
const handleDeleteSystem = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该系统吗？', '提示', { type: 'warning' })
    await deleteSystem(row.id)
    ElMessage.success('删除成功')
    loadSystemList()
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}
const handleToggleSystem = async (row) => {
  try {
    await updateSystemStatus(row.id, row.status === 'enabled' ? 'disabled' : 'enabled')
    ElMessage.success('操作成功')
    loadSystemList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}
const handleTestSystem = async (row) => {
  try {
    await testSystem(row.id)
    ElMessage.success('测试成功')
  } catch (error) {
    ElMessage.error('测试失败')
  }
}
const handleSyncSystem = async (row) => {
  try {
    await syncSystem(row.id)
    ElMessage.success('同步成功')
  } catch (error) {
    ElMessage.error('同步失败')
  }
}

// 消息队列
const queueList = ref([])
const queueLoading = ref(false)
const queuePage = ref(1)
const queuePageSize = ref(20)
const queueTotal = ref(0)
const queueSearch = ref('')
const queueDialogVisible = ref(false)
const queueDialogTitle = ref('')
const queueFormRef = ref(null)
const queueForm = reactive({ id: '', name: '', type: '', server: '', consumerCount: 1, remark: '' })
const queueRules = {
  name: [{ required: true, message: '请输入队列名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择队列类型', trigger: 'change' }],
  server: [{ required: true, message: '请输入服务器地址', trigger: 'blur' }],
  consumerCount: [{ required: true, message: '请输入消费者数', trigger: 'blur' }]
}

const loadQueueList = async () => {
  try {
    queueLoading.value = true
    const res = await getQueueList({
      page: queuePage.value,
      pageSize: queuePageSize.value,
      search: queueSearch.value
    })
    queueList.value = res.data.list
    queueTotal.value = res.data.total
  } catch (error) {
    ElMessage.error('加载队列列表失败')
  } finally {
    queueLoading.value = false
  }
}

const handleCreateQueue = () => {
  queueDialogTitle.value = '新增队列'
  Object.assign(queueForm, { id: '', name: '', type: '', server: '', consumerCount: 1, remark: '' })
  queueDialogVisible.value = true
}
const handleEditQueue = (row) => {
  queueDialogTitle.value = '编辑队列'
  Object.assign(queueForm, row)
  queueDialogVisible.value = true
}
const handleSaveQueue = async () => {
  if (!queueFormRef.value) return
  try {
    await queueFormRef.value.validate()
    if (queueForm.id) {
      await updateQueue(queueForm)
      ElMessage.success('更新成功')
    } else {
      await createQueue(queueForm)
      ElMessage.success('创建成功')
    }
    queueDialogVisible.value = false
    loadQueueList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}
const handleDeleteQueue = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该队列吗？', '提示', { type: 'warning' })
    await deleteQueue(row.id)
    ElMessage.success('删除成功')
    loadQueueList()
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}
const handleToggleQueue = async (row) => {
  try {
    await updateQueueStatus(row.id, row.status === 'enabled' ? 'disabled' : 'enabled')
    ElMessage.success('操作成功')
    loadQueueList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}
const handleMonitorQueue = async (row) => {
  try {
    await monitorQueue(row.id)
    ElMessage.success('监控成功')
  } catch (error) {
    ElMessage.error('监控失败')
  }
}
const handlePurgeQueue = async (row) => {
  try {
    await purgeQueue(row.id)
    ElMessage.success('清空成功')
    loadQueueList()
  } catch (error) {
    ElMessage.error('清空失败')
  }
}

// 监控告警
const monitorList = ref([])
const monitorLoading = ref(false)
const monitorPage = ref(1)
const monitorPageSize = ref(20)
const monitorTotal = ref(0)
const monitorSearch = ref('')
const monitorDialogVisible = ref(false)
const monitorDialogTitle = ref('')
const monitorFormRef = ref(null)
const monitorForm = reactive({ id: '', name: '', type: '', target: '', remark: '' })
const monitorRules = {
  name: [{ required: true, message: '请输入监控名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择监控类型', trigger: 'change' }],
  target: [{ required: true, message: '请输入监控对象', trigger: 'blur' }]
}

const loadMonitorList = async () => {
  try {
    monitorLoading.value = true
    const res = await getMonitorList({
      page: monitorPage.value,
      pageSize: monitorPageSize.value,
      search: monitorSearch.value
    })
    monitorList.value = res.data.list
    monitorTotal.value = res.data.total
  } catch (error) {
    ElMessage.error('加载监控列表失败')
  } finally {
    monitorLoading.value = false
  }
}

const handleCreateMonitor = () => {
  monitorDialogTitle.value = '新增监控'
  Object.assign(monitorForm, { id: '', name: '', type: '', target: '', remark: '' })
  monitorDialogVisible.value = true
}
const handleEditMonitor = (row) => {
  monitorDialogTitle.value = '编辑监控'
  Object.assign(monitorForm, row)
  monitorDialogVisible.value = true
}
const handleSaveMonitor = async () => {
  if (!monitorFormRef.value) return
  try {
    await monitorFormRef.value.validate()
    if (monitorForm.id) {
      await updateMonitor(monitorForm)
      ElMessage.success('更新成功')
    } else {
      await createMonitor(monitorForm)
      ElMessage.success('创建成功')
    }
    monitorDialogVisible.value = false
    loadMonitorList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}
const handleDeleteMonitor = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该监控吗？', '提示', { type: 'warning' })
    await deleteMonitor(row.id)
    ElMessage.success('删除成功')
    loadMonitorList()
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}
const handleToggleMonitor = async (row) => {
  try {
    await updateMonitorStatus(row.id, row.status === 'enabled' ? 'disabled' : 'enabled')
    ElMessage.success('操作成功')
    loadMonitorList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}
const handleTestMonitor = async (row) => {
  try {
    await testMonitor(row.id)
    ElMessage.success('测试成功')
  } catch (error) {
    ElMessage.error('测试失败')
  }
}
const handleViewHistory = async (row) => {
  try {
    await getMonitorHistory(row.id)
    ElMessage.success('获取历史成功')
  } catch (error) {
    ElMessage.error('获取历史失败')
  }
}

// 初始化
onMounted(() => {
  loadSystemList()
  loadQueueList()
  loadMonitorList()
})
</script>

<style lang="scss" scoped>
.integration-management {
  padding: 20px;
  .integration-tabs {
    .card-header {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 20px;
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 